package com.lxm.algorithm.circleQueue;

import java.util.AbstractQueue;
import java.util.Arrays;
import java.util.Iterator;

public class ArrayCircleQueue<T> extends AbstractQueue<T> {
    private int size;
    private int capacity;
    private Object[] array;
    private int head;
    private int tail;

    public ArrayCircleQueue(int capacity) {
        this.size = 0;
        this.array = new Object[capacity];
        this.head = tail = 0;
        this.capacity = capacity;
    }

    public ArrayCircleQueue() {
        this(10);
    }

    private boolean enQueue(T t) {
        // 如果结尾加1head说明队列已满
        if ((tail + 1) % capacity == head) {
            return false;
        }
        array[tail] = t;
        tail = (tail + 1) % capacity;
        size++;
        return true;
    }

    private T deQueue() {
        if (head == tail) {
            return null;
        }
        T e = (T) array[head];
        head = (head + 1) % capacity;
        size--;
        return e;
    }

    @Override
    public Iterator<T> iterator() {
        return null;
    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public boolean offer(T t) {
        return enQueue(t);
    }

    @Override
    public T poll() {
        return deQueue();
    }

    @Override
    public T peek() {
        return (T) array[head];
    }

    @Override
    public String toString() {
        return "CircularQueue{" +
                "values=" + Arrays.toString(array) +
                ", capacity=" + capacity +
                ", head=" + head +
                ", tail=" + tail +
                '}';
    }
}
